<template>
    <a-modal :visible="visible"
             :mask-closable="false"
             :footer="null"
             :title="title"
             @cancel="close">
        <!-- 表单 -->
        <a-form :form="dataForm" @submit="handleSubmit"
                label-align="left"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span : 20 }">
            <a-form-item style="display: none;">
                <a-input type="text" v-decorator="[ 'id' ]" />
            </a-form-item>
            <slot name="formItem" />
            <div style="text-align: right;">
                <a-button style="margin-right: 10px;" @click="close">取消</a-button>
                <a-button type="primary" html-type="submit" :loading="submitBtnLoading">保存</a-button>
            </div>
        </a-form>
    </a-modal>
</template>

<script>
    export default {
        data(){
            return {
                //  数据表单
                dataForm : this.$form.createForm(this),
                //  标题
                title : '',
                //  显示/隐藏
                visible : false,
                //  提交按钮的加载状态
                submitBtnLoading : false,
                //  API接口
                apiInterface : () => {},
                //  回调接口
                callbackFn : () => {},
            };
        },
        methods : {
            //  打开
            open : function(params){
                let $this = this;
                $this.title = params['title'];
                $this.apiInterface = params['apiInterface'];
                $this.callbackFn = params['callbackFn'];
                if (params['data']){
                    $this.setFieldsValue(params['data']);
                }
                $this.visible = true;
            },
            //  关闭
            close : function (e) {
                e.preventDefault();
                this.dataForm.resetFields();
                this.visible = false;
            },
            //  设置表单的值
            setFieldsValue : function(params){
                this.$nextTick(() => this.dataForm.setFieldsValue(params));
            },
            //  监听表单提交事件
            handleSubmit : function (e) {
                e.preventDefault();
                let $this = this;
                $this.dataForm.validateFields((err, params) => {
                    if (!err){
                        $this.submitBtnLoading = true;
                        $this.apiInterface(params).then(() => {
                            //  关闭当前窗口
                            $this.close(e);
                            //  调用接口
                            $this.callbackFn(params);
                        }).finally(() => $this.submitBtnLoading = false);
                    }
                });
            }
        }
    }
</script>
